package com.warm.mini.wework.service.invoke;

import com.alibaba.fastjson.JSONObject;
import com.warm.mini.wework.config.WeworkConfigProperties;
import com.warm.mini.wework.config.TanzsayConfig;
import com.warm.mini.wework.constant.WeworkConst;
import com.warm.mini.wework.feign.WeworkApiRest;
import com.warm.mini.wework.util.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * @Description 授权
 * @Author warmchuang
 * @Date 2022/2/11 11:39
 */
@Slf4j
@Service
public class WeworkAuthServiceImpl {

    /**
     * todo: 后面多个主体在做拓展 --> resource 获取主体
     *                        --> agentId 应用
     */
    @Resource
    private TanzsayConfig tanzsayConfig;
    @Resource
    private AccessTokenServiceImpl accessTokenService;

    public void autoAuth(String resource, String appCode, String targetUrl){
        try {
            // 重新授权
            String backUrl = String.format(WeworkConst.AUTH_BACK_URL, resource, appCode, URLEncoder.encode(targetUrl, "utf-8"));
            String authUrl = String.format(WeworkConst.WX_OAUTH2_URL, WeworkConst.Subject.getByName(resource).getCorpId(), URLEncoder.encode(backUrl, "utf-8"));

            try {
                ServletUtil.getResponse().sendRedirect(authUrl);
            } catch (IOException e) {
                log.info("wework application autoAuth sendRedirect error:{}", e.getMessage(), e);
            }
        } catch (UnsupportedEncodingException e) {
            log.info("wework sidebar autoAuth error:{}", e.getMessage(), e);
        }
    }

    /**
     * 根据 resource appCode 获取指定
     * @param resource
     * @param agentId
     * @param targetUrl
     * @param code
     */
    public void authBack(String resource, String agentId, String targetUrl, String code){
        // todo 后续扩展为多应用配置
        WeworkConfigProperties config = tanzsayConfig.buildApplicationConfig().get(agentId);
        String accessToken = accessTokenService.getAccessToken(config);
        // 拿到授权信息
        JSONObject resp = WeworkApiRest.get().getUserInfo(accessToken, code);
        String userId = null;
        String userType = null;
        if (resp.containsKey("UserId")) {
            userId = resp.getString("UserId");
            userType = "contact";
        } else if (resp.containsKey("external_userid")) {
            userId = resp.getString("external_userid");
            userType = "external_contact";
        }
        log.info("get auth res:{}", resp);
        // todo 做缓存或者存 cookie

        try {
            // 授权拼接到链接上
            ServletUtil.getResponse().sendRedirect(setAuthedUrl(targetUrl, resource, userId, userType));
        } catch (IOException e) {
            log.info("wework application autoAuth sendRedirect error:{}", e.getMessage(), e);
        }
    }

    private String setAuthedUrl(String targetUrl, String resource, String userId, String userType){
        log.info("set authUrl: targetUrl:[{}] userId:{}, userType:{}, resource:{}", targetUrl, userId, userType, resource);
        StringBuilder sb = new StringBuilder(targetUrl);
        sb.append("?").append("resource").append("=").append(resource);
        sb.append("&").append("userId").append("=").append(userId);
        sb.append("&").append("userType").append("=").append(userType);
        return sb.toString();
    }
}
